package cs.fsu.fsview;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class DownloadThread extends Thread {

	private static final String TAG = "cs.fsu.fsview";
	private String[] sections;
	public StoryAdapter[] stories;
	public boolean runThread = true;
	private Context context;
	private volatile Handler handler;
	
	DownloadThread(Context context, Handler handler){
		this.handler = handler;
		this.context = context;
		sections = context.getResources().getStringArray(R.array.SectionLinks);
	}
	
	@Override
	public void run() {
		stories = getStories();
		handler.sendEmptyMessage(0);
		
		
		while(runThread){
			;
		}
		
	}
	
	private StoryAdapter[] getStories(){

		//Log.i(TAG, "getStories " + sections.length);

		StoryAdapter[] tmp = new StoryAdapter[sections.length];

		Log.i(TAG, "Getting Stories " + tmp.length);

		int length = tmp.length;
		for(int i = 0; i < length; i++){
			Log.i(TAG, "Getting sectinon " + i);
			tmp[i] = parseHtml(sections[i]);
		}

		return tmp;
	}

	private StoryAdapter parseHtml(String url){

		HtmlCleaner cleaner = new HtmlCleaner();
		//CleanerProperties props = cleaner.getProperties();
		//props.setAdvancedXmlEscape(true);
		//props.setTranslateSpecialEntities(false);
		//props.setRecognizeUnicodeChars(false);

		URL source;
		TagNode node = null;

		try {
			source = new URL(url);
			node = cleaner.clean(source.openStream(), "UTF-8");

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		node = node.findElementByAttValue("id", "leftColumn", true, true);

		Log.i(TAG,"default encoding = " + System.getProperty("file.encoding"));

		/*
	if(node != null)
		Log.i(TAG,cleaner.getInnerHtml(node));
	else
		Log.i(TAG, "Node not found");
		 */

		//node.findElementHavingAttribute(arg0, arg1);
		final TagNode[] storyHeader = node.getElementsByAttValue("class", "title", false, false);
		TagNode[] storyPreview = node.getElementsByName("p", false);

		for(int i = 0; i < storyHeader.length; i++){
			storyHeader[i].getText();
			//Log.i(TAG, "Story Preview <" + storyPreview[i].getText() + ">");
		}

		final StoryAdapter stories = new StoryAdapter(context, storyHeader, storyPreview);

		Log.i(TAG, "Setting Adapter");


		return stories;
	}

}
